package com.cy.selenium;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.cy.bean.DyBarrageMessage;
import com.cy.listener.DyBarrageListener;
import com.cy.queue.UniqueQueue;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @Description: 描述
 * @Author：chenguifu
 * @Date：2022/11/21 18:32
 * @Company：公司
 * @Version：V1.0
 */
@Data
public class DySelenium2 {
    /** 抖音直播间地址 **/
    private final String liveUrl;

    /** 是否过滤用户进入直播间进场弹幕消息 **/
    private final boolean filterJoinUserMsg;

    /** 抖音弹幕监听器 **/
    private final DyBarrageListener dyBarrageListener;

    /** 弹幕队列 最大容量2000 **/
    private UniqueQueue<DyBarrageMessage> uniqueQueue = new UniqueQueue<DyBarrageMessage>(200);

    /**礼物列表**/
    private Map<String,String> giftMap=new HashMap<>();
    public DySelenium2(String liveUrl, boolean filterJoinUserMsg, DyBarrageListener dyBarrageListener) {
        this.liveUrl = liveUrl;
        this.dyBarrageListener = dyBarrageListener;
        this.filterJoinUserMsg = filterJoinUserMsg;
    }
    public void start() {
        new Thread(new Runnable() {

            public void run() {
                while (true) {
                    try {
                        DyBarrageMessage barrageMessage = uniqueQueue.poll();
                        if (barrageMessage != null) {
                            dyBarrageListener.consume(barrageMessage);
                        }
                        Thread.sleep(5*100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {

            public void run() {
                try {
                    String path = System.getProperty("user.dir");
                    String fileName = System.getProperty("os.name").toLowerCase().startsWith("windows")
                            ? "/driver/chromedriver119.0.6045.105.exe" //chromedriver117.0.5938.88.exe
                            : "/driver/chromedriver";
                    System.setProperty("webdriver.chrome.driver", path + fileName);
                    ChromeOptions options = new ChromeOptions();
                    options.addArguments("headless");
                    ChromeDriver driver = new ChromeDriver(options);
                    driver.get(liveUrl);
                    long sleepMillis=30;
                    System.out.println("沉睡："+sleepMillis+" s");
                    Thread.sleep(sleepMillis*10);
                    System.out.println("沉睡："+sleepMillis+" s 结束");
                    //礼物抓取
//                    Map<String, String> giftList = getGiftList(driver);
                    //礼物读取
                    Map<String, String> giftList=readGiftList();
                    System.out.println("giftList size:"+ giftList.size());
                    System.out.println("giftList:\n"+ JSON.toJSONString(giftList));
                    giftMap=giftList;
                    while (true) {
                        try {
                            //获取右边消息
                            List<WebElement> elements = driver.findElements(By.cssSelector(".webcast-chatroom___items"));
                            if(elements.size()>0){
                                String innerHTML = elements.get(elements.size() - 1).getAttribute("innerHTML");
                                addToQueue1(innerHTML);
                            }
                            Thread.sleep(5*10);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void addToQueue(String html) {
        Elements items = Jsoup.parse(html).select(".webcast-chatroom___item");
        for (Element item : items) {
            if (item.selectFirst(".webcast-chatroom__room-message") != null) {
                continue;
            }
            Element textElement = item.selectFirst("span[class='webcast-chatroom___content-with-emoji-text']");
            if (filterJoinUserMsg && textElement == null) {
                continue;
            }
            DyBarrageMessage barrageMessage = new DyBarrageMessage();
            if (textElement != null) {
                barrageMessage.setMessage(textElement.text());
            }
            barrageMessage.setId(item.attr("data-id"));
            Element nickElement = item.selectFirst("span[class='rc30lnLh']");
            if (nickElement != null) {
                barrageMessage.setNickname(nickElement.text());
            }
            uniqueQueue.add(barrageMessage);
        }
    }
    private void addToQueue1(String html) {
        Elements items = Jsoup.parse(html).select(".webcast-chatroom___item");
        for (Element item : items) {
            Element rootMsg = item.selectFirst(".webcast-chatroom__room-message");
            if ( rootMsg!= null) {
                continue;
            }
            Element textElement = item.selectFirst("span[class='webcast-chatroom___content-with-emoji-text']");
            Element giftTextElement = item.selectFirst("span[class='HCajOVT6']");
            if (filterJoinUserMsg && (textElement == null&&giftTextElement==null)) {
                continue;
            }
            DyBarrageMessage barrageMessage = new DyBarrageMessage();
            if (textElement != null) {
                barrageMessage.setMessage(textElement.text());
            }
            if(giftTextElement!=null){
//                System.out.println("giftTextElement:"+giftTextElement.html());
                String giftText="送出了";
                Element aElement = giftTextElement.selectFirst("img[class='sG3bJJhR']");
                if (aElement != null) {
                    String src = giftTextElement.select("img").get(0).attr("src");
                    src=src.substring(src.lastIndexOf("/")+1);
                    String giftName = giftMap.get(src);
                    barrageMessage.setGiftName(giftName);
                    giftText+=giftName;
                    barrageMessage.setGiftImgUrl(src);
                    barrageMessage.setMessage(giftText);
                    Element element = item.selectFirst("span[class='xvIN8CM4']");
                    String text = element.text();
                    Integer giftNum=getStrNum(text);
                    if(giftNum!=null){
                        barrageMessage.setGiftNum(giftNum);
                    }
                }
            }
            barrageMessage.setId(item.attr("data-id"));
            Element nickElement = item.selectFirst("span[class='rc30lnLh']");
            if (nickElement != null) {
                barrageMessage.setNickname(nickElement.text());
            }
            Element aElement = item.selectFirst("img");
            if (aElement != null) {
                barrageMessage.setAvatar(aElement.attr("src"));
            }

            uniqueQueue.add(barrageMessage);
        }
    }

    //从文本里面读取礼物列表
    private Map<String,String> readGiftList(){
        String path = System.getProperty("user.dir")+"\\src\\main\\resources\\giftJSON.txt";
        String string = FileUtil.readUtf8String(path);
        Map map = JSON.parseObject(string, Map.class);
        return map;
    }

    public static Integer getStrNum(String strOnNum){
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(strOnNum);
        String result = m.replaceAll("").trim();
        return StringUtils.isEmpty(result)?null:Integer.valueOf(result);
    }

    public static void main(String[] args) {
        // 后缀为直播间id
        System.out.println("启动时间"+new Date());
        String url = "https://live.douyin.com/890013832180";
        DyBarrageListener listener = message -> {
            String msg = message.getMessage();
            Integer giftNum = message.getGiftNum();
            if(giftNum!=null){
                msg=msg+" X"+giftNum;
            }
            String giftImgUrl = message.getGiftImgUrl();
            giftImgUrl=giftImgUrl!=null?(" giftImg:"+giftImgUrl+",giftName:"+message.getGiftName()):"";
            String msgLog=new SimpleDateFormat("HH:mm:ss").format(new Date()) + "【ID:" +message.getId()+",nickname:"+ message.getNickname()
                    + "】" + msg + "-【ID：" + message.getId() +"】"+giftImgUrl;
            System.out.println(msgLog);
        };
        new DySelenium2(url, true, listener).start();
    }
}